<?php

namespace App\Traits;

use App\Utils\HelperUtils;
use Hyperf\DB\DB;
use function Hyperf\Collection\collect;
/**
 * mysql
 */
trait MysqlTrait
{

    /**
     * 按唯一索引批量写入或更新操作
     * @param array $rows
     * @param array $update
     * @return false
     */
    public  function upsert(array $rows, array $update = [],string $tableName = null)
    {
        $conn = DB::connection($this->connection);
        if(!empty($tableName)) $this->table = $tableName;
        if (!$rows) {
            return false;
        }
        $keys = $valuesInsert = [];
        foreach($rows as $k => $item)
        {
            if($k == 0)
            {
                $keys = array_keys($item);
            }
            //剔除写入值中的单双引号，防止拼装的sql 报错
            foreach ($item as &$val)
            {
                if(HelperUtils::isJson($val))
                {
                    $val = trim($val);
                }else{
                    $val = is_string($val) ? addslashes($val) : $val;
                }
            }
            $valuesInsert[] = array_values($item);
        }
        $valuesStr = collect($valuesInsert)->map(function ($value){
            return  "('".implode("','",$value)."')";
        })->implode(',');

        $columns = array_keys(reset($rows));
        $sql = "INSERT INTO `{$this->table}` (`".implode('`,`',$keys)."`) VALUES {$valuesStr}  ON DUPLICATE KEY UPDATE ";
        $update = $update ?: $columns;
        $sql .= collect($update)->map(function ($value){
            return   "`$value`=VALUES(`$value`)";
        })->implode(',');
        unset($valuesInsert,$valuesStr,$update,$keys,$columns);
        return $conn->insert($sql);
    }
}